from sqlalchemy import insert, select

from owl_admin.ext import db
from owl_ai.domain.agent_config_entity import AgentConfigEntity
from owl_ai.domain.agent_config_po import AgentConfigPO
from owl_common.sqlalchemy.model import ColumnEntityList
from owl_common.sqlalchemy.transaction import Transactional


class AgentConfigMapper:
    default_fields = ['id', 'name', 'type', 'graph']

    default_columns = ColumnEntityList(AgentConfigPO, default_fields, False)

    @classmethod
    @Transactional(db.session)
    def insert(cls, agent_config: AgentConfigEntity) -> int:
        fields = ['id', 'name', 'type', 'graph']
        data = agent_config.model_dump(include=fields, exclude_none=True, exclude_unset=True)
        stmt = insert(AgentConfigPO).values(data)
        out = db.session.execute(stmt).inserted_primary_key
        return out[0] if out else 0

    @classmethod
    @Transactional(db.session)
    def update(cls, agent_config):
        pass

    @classmethod
    @Transactional(db.session)
    def delete(cls, agent_config):
        pass

    @classmethod
    @Transactional(db.session)
    def get(cls, agent_config: AgentConfigEntity):
        criteria = []
        if agent_config.id:
            criteria.append(AgentConfigPO.id == agent_config.id)

        stmt = select(*cls.default_columns).where(*criteria)
        row = db.session.execute(stmt).one_or_none()
        return cls.default_columns.cast(row, AgentConfigEntity) if row else None

    @classmethod
    @Transactional(db.session)
    def select_by_id(cls, config_id: int):
        criteria = [AgentConfigPO.id == config_id]
        stmt = select(*cls.default_columns).where(*criteria)
        row = db.session.execute(stmt).one_or_none()
        return cls.default_columns.cast(row, AgentConfigEntity) if row else None

    @classmethod
    @Transactional(db.session)
    def list(cls, agent_config):
        pass
